package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetMealServiceImpl  implements SetMealService {
@Autowired
private SetMealMapper setMealMapper;
@Autowired
private CheckGroupMapper checkGroupMapper;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private RedisTemplate redisTemplate;
@Value("${freemarker.out.path}")
private String outputpath ;

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    public Setmeal findById(Integer id) {
        return setMealMapper.findById(id);
    }

    /**
     * 新增体检套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    public boolean add(Setmeal setmeal, List<Integer> checkgroupIds) {
        if (setMealMapper.add(setmeal)){
            for (int id :checkgroupIds)
            setMealMapper.addGroupIdInSetmeal(setmeal.getId(),id);
        }else
            return false;
        Integer setmealId = setmeal.getId();
        //中间表中添加（封装为方法可复用）
        this.setCheckGroupAndSetmeal(setmealId,(Integer[]) checkgroupIds.toArray());
        //新增后重新生成的静态页面
        AfterAddHtml();
        return true;

    }
    //新增后重新生成的静态页面
    private void AfterAddHtml() {
        //模板文件中需要的套餐集合
        List<Setmeal> setmealList =setMealMapper.findAll();
        //生成套餐列表静态页面
        Map<String,Object> map = new HashMap<>();
        map.put("setmealList",setmealList);
        this.html("mobile_setmeal.ftl","m_setmeal.html",map);
        //生成套餐详情静态页面
        for (Setmeal setmeal : setmealList) {
            Map<String,Object> map1 = new HashMap<>();
            map1.put("setmeal",setMealMapper.findById(setmeal.getId()));
            html("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map1);
        }
    }

    //生成原始静态页面，
    public void html(String templateName,String htmlName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            out=new FileWriter(new File(outputpath+"/"+htmlName));
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑
     * @param setmeal
     * @param checkGroupIds
     * @return
     */
    public boolean edit(Setmeal setmeal, List<Integer> checkGroupIds) {

        //应该先判断长度
        //多则删，少则加
        //获取setMeal对应的项目组id
        int temp = 0;
        List<Integer> list = checkGroupMapper.findCheckGroupIdsBySetmealId(setmeal.getId());
        if(setMealMapper.edit(setmeal)){
            if (checkGroupIds.size()>list.size()){
                for(int i =0;i<list.size();i++){
                    setMealMapper.editSetMealInGroup(list.get(i),setmeal.getId(),checkGroupIds.get(i));
                    temp++;
                }
                for (;temp<checkGroupIds.size();temp++){
                    setMealMapper.insert(checkGroupIds.get(temp),setmeal.getId());
                }
            }else{
                for (int i = 0;i<checkGroupIds.size();i++){
                    setMealMapper.editSetMealInGroup(list.get(i),setmeal.getId(),checkGroupIds.get(i));
                    temp++;
                }
                for(;temp<list.size();temp++){
                    setMealMapper.delete(list.get(temp),setmeal.getId());
                }
            }
        }else
            return false;
        return true;
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = (Page<Setmeal>) setMealMapper.findAll();
        return new PageResult(page.getTotal(),page.getResult());
    }

    //获取照片所有路径
    public List<String> getImgs() {
        return setMealMapper.FindImgs();
    }

    /**
     * 封装的往中间表添加数据
     * @param setmealId
     * @param checkgroupIds
     */
    private void setCheckGroupAndSetmeal(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setMealMapper.addCheckGroupAndSetmeal(map);
            }
        }
    }

}
